﻿package com.neriksworkshop.colourLoversDemos.wordPatches.view
{
	import com.neriksworkshop.lib.colourLovers.items.IGraphicItem;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.AntiAliasType;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	
	/**
	 * ...
	 * @author Erik
	 */
	public class MainView extends Sprite
	{
		private static const DEFAULT_TEXT:String = "word?";
		
		private var _tf:TextField;
		
		private var _currentSubmittedText:String;
		
		private var _patches:/*Patch*/Array = new Array();
		
		public function MainView() 
		{
			
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage)

		}
		
		private function onAddedToStage(e:Event):void 
		{
									
			graphics.beginFill(0xff0000, 0);
			graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
			
			_tf = new TextField();
			_tf.type = TextFieldType.INPUT;
			_tf.border = true;
			_tf.autoSize = TextFieldAutoSize.LEFT;
			//_tf.antiAliasType = AntiAliasType.ADVANCED;
			//_tf.embedFonts = true			
			_tf.defaultTextFormat = Params.PATCH_FMT;
			_tf.filters = Params.PATCH_FILTERS;
						
			addEventListener(MouseEvent.CLICK, onClick);
			
			addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown)
			
		}
		
		
		private function onClick(e:MouseEvent):void 
		{
			_tf.x = e.stageX;
			_tf.y = e.stageY;
			_tf.text = DEFAULT_TEXT;
			_tf.setSelection(0, _tf.text.length)
			stage.focus = _tf;
			addChild(_tf);
		}
		

		private function onKeyDown(e:KeyboardEvent):void 
		{
			if (e.keyCode == 13 && _tf.stage)
			{
				_currentSubmittedText = _tf.text;
				var patchId:int = createPatch();
				_tf.text = "";
				removeChild(_tf);
				
			}
			
		}		
		
		
		private function createPatch():int
		{
			var p:Patch = new Patch(_tf.text, _patches.length);
			p.x = _tf.x;
			p.y = _tf.y;
			addChild(p);
			_patches.push(p);
			p.dispatchEvent(new Event('patchAdded', true));
			return p.id;
		}
		
		public function setPatchData(patchId:int, items:Array, type:String):void
		{
			var patch:Patch = _patches[patchId];
			if (type == "palettes") patch.setPalettes(items) else patch.setPatterns(items);
		}
		
		
		
		public function get currentSubmittedText():String { return _currentSubmittedText; }
		

		
	}
	
}